﻿// -------------------------------------------------------------------------------------------------------------------------------
// <copyright file="CrsSparseMatrixExtensions.cs" company="Exul">
//     Copyright (c) Exul. All rights reserved.
// </copyright>
// <author>
//     Exul
// </author>
// -------------------------------------------------------------------------------------------------------------------------------

namespace ExulLibrary.Mathematics.LinearAlgebra.Sequential
{
    #region Usings

    using System;
    using System.Globalization;

    using ExulLibrary.Exceptions;
    using ExulLibrary.Mathematics.LinearAlgebra.Exceptions;

    #endregion

    /// <summary>
    ///     Provides extension methods for <see cref="CrsSparseMatrix{T}"/>.
    /// </summary>
    public static class CrsSparseMatrixExtensions
    {
        #region Methods

        #region public

        /// <summary>
        ///     Assigns the second matrix to the specified elements of the first matrix.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="target">
        ///     The matrix whose elements should be assigned.
        /// </param>
        /// <param name="targetRowsIndexes">
        ///     The collection of zero-based indexes of rows of target elements.
        /// </param>
        /// <param name="targetColumnsIndexes">
        ///     The collection of zero-based indexes of columns of target elements.
        /// </param>
        /// <param name="source">
        ///     The matrix whose elements should be copied.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="target"/> is <see langword="null"/>.
        ///     <para>
        ///         --or--
        ///     </para>
        ///     <para>
        ///         <paramref name="source"/> is <see langword="null"/>.
        ///     </para>
        ///     <para>
        ///         --or--
        ///     </para>
        ///     <para>
        ///         <paramref name="targetRowsIndexes"/> is <see langword="null"/>.
        ///     </para>
        ///     <para>
        ///         --or--
        ///     </para>
        ///     <para>
        ///         <paramref name="targetColumnsIndexes"/> is <see langword="null"/>.
        ///     </para>
        /// </exception>
        /// <exception cref="ElementIndexIsOutOfRangeException">
        ///     An element of <paramref name="targetRowsIndexes"/> is negative or greater than or equal to
        ///     rows count of <paramref name="target"/>.
        ///     <para>
        ///         --or--
        ///     </para>
        ///     <para>
        ///         An element of <paramref name="targetColumnsIndexes"/> is negative or greater than or equal to
        ///         columns count of <paramref name="target"/>.
        ///     </para>
        /// </exception>
        /// <exception cref="ReadOnlyMatrixElementException">
        ///     An element to assign specified by <paramref name="targetRowsIndexes"/> and <paramref name="targetColumnsIndexes"/>
        ///     is not in the portrait of <paramref name="target"/>.
        /// </exception>
        /// <remarks>
        ///     The number of rows of <paramref name="source"/> to assign to <paramref name="target"/> is determined as
        ///     min(<paramref name="targetRowsIndexes"/>.Length, <paramref name="source"/>.RowsCount).
        ///     The number of columns of <paramref name="source"/> to assign to <paramref name="target"/> is determined as
        ///     min(<paramref name="targetColumnsIndexes"/>.Length, <paramref name="source"/>.ColumnsCount).
        /// </remarks>
        public static void Assign<T>(
            this CrsSparseMatrix<T> target,
            int[] targetRowsIndexes,
            int[] targetColumnsIndexes,
            RMDenseMatrix<T> source)
        {
            #if SAFE

            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            if (targetRowsIndexes == null)
            {
                throw new ArgumentNullException("targetRowsIndexes");
            }

            if (targetColumnsIndexes == null)
            {
                throw new ArgumentNullException("targetColumnsIndexes");
            }

            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            #endif

            var targetRowsCount = target.RowsCount;
            var targetColumnsCount = target.ColumnsCount;
            var targetRowsBegins = target.RowsBegins;
            var targetColumns = target.ColumnsIndexes;
            var targetValues = target.Values;
            var sourceValues = source.Values;

            var rowsCountToAssign = Math.Min(targetRowsIndexes.Length, source.RowsCount);
            var columnsCountToAssign = Math.Min(targetColumnsIndexes.Length, source.ColumnsCount);
            for (var rowIndex = 0; rowIndex < rowsCountToAssign; rowIndex++)
            {
                var rowElementIndex = targetRowsIndexes[rowIndex];

                #if SAFE

                if ((rowElementIndex < 0) || (targetRowsCount <= rowElementIndex))
                {
                    var argumentName = string.Format(CultureInfo.CurrentCulture, "targetRowsIndexes[{0}]", rowIndex);
                    throw new ElementIndexIsOutOfRangeException(argumentName, rowElementIndex, 0, targetRowsCount - 1);
                }

                #endif

                var targetStartIndex = targetRowsBegins[rowElementIndex];
                var targetEndIndex = targetRowsBegins[rowElementIndex + 1];

                var sourceRow = sourceValues[rowIndex];

                for (var columnIndex = 0; columnIndex < columnsCountToAssign; columnIndex++)
                {
                    var columnElementIndex = targetColumnsIndexes[columnIndex];

                    #if SAFE

                    if ((rowIndex == 0) && ((columnElementIndex < 0) || (targetColumnsCount <= columnElementIndex)))
                    {
                        var argumentName = string.Format(CultureInfo.CurrentCulture, "targetColumnsIndexes[{0}]", columnIndex);
                        throw new ElementIndexIsOutOfRangeException(argumentName, columnElementIndex, 0, targetColumnsCount - 1);
                    }

                    #endif

                    var position = targetStartIndex;
                    while ((position < targetEndIndex) && (targetColumns[position] < columnElementIndex))
                    {
                        position++;
                    }

                    // if element is not found, skip it
                    if ((position == targetEndIndex) || (targetColumns[position] != columnElementIndex))
                    {
                        #if SAFE

                        throw new ReadOnlyMatrixElementException("target", rowElementIndex, columnElementIndex);

                        #else

                        continue;

                        #endif
                    }

                    targetValues[position] = sourceRow[columnIndex];
                }
            }
        }

        /// <summary>
        ///     Assigns the second matrix to the specified elements of the first matrix.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="target">
        ///     The matrix whose elements should be assigned.
        /// </param>
        /// <param name="targetRowsIndexes">
        ///     The collection of zero-based indexes of rows of target elements.
        /// </param>
        /// <param name="targetColumnsIndexes">
        ///     The collection of zero-based indexes of columns of target elements.
        /// </param>
        /// <param name="source">
        ///     The matrix whose elements should be copied.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="target"/> is <see langword="null"/>.
        ///     <para>
        ///         --or--
        ///     </para>
        ///     <para>
        ///         <paramref name="source"/> is <see langword="null"/>.
        ///     </para>
        ///     <para>
        ///         --or--
        ///     </para>
        ///     <para>
        ///         <paramref name="targetRowsIndexes"/> is <see langword="null"/>.
        ///     </para>
        ///     <para>
        ///         --or--
        ///     </para>
        ///     <para>
        ///         <paramref name="targetColumnsIndexes"/> is <see langword="null"/>.
        ///     </para>
        /// </exception>
        /// <exception cref="ElementIndexIsOutOfRangeException">
        ///     An element of <paramref name="targetRowsIndexes"/> is negative or greater than or equal to
        ///     rows count of <paramref name="target"/>.
        ///     <para>
        ///         --or--
        ///     </para>
        ///     <para>
        ///         An element of <paramref name="targetColumnsIndexes"/> is negative or greater than or equal to
        ///         columns count of <paramref name="target"/>.
        ///     </para>
        /// </exception>
        /// <exception cref="ReadOnlyMatrixElementException">
        ///     An element to assign specified by <paramref name="targetRowsIndexes"/> and <paramref name="targetColumnsIndexes"/>
        ///     is not in the portrait of <paramref name="target"/>.
        /// </exception>
        /// <remarks>
        ///     The number of rows of <paramref name="source"/> to assign to <paramref name="target"/> is determined as
        ///     min(<paramref name="targetRowsIndexes"/>.Length, <paramref name="source"/>.RowsCount).
        ///     The number of columns of <paramref name="source"/> to assign to <paramref name="target"/> is determined as
        ///     min(<paramref name="targetColumnsIndexes"/>.Length, <paramref name="source"/>.ColumnsCount).
        /// </remarks>
        public static void Assign<T>(
            this CrsSparseMatrix<T> target,
            int[] targetRowsIndexes,
            int[] targetColumnsIndexes,
            RMFlattenDenseMatrix<T> source)
        {
            #if SAFE

            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            if (targetRowsIndexes == null)
            {
                throw new ArgumentNullException("targetRowsIndexes");
            }

            if (targetColumnsIndexes == null)
            {
                throw new ArgumentNullException("targetColumnsIndexes");
            }

            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            #endif

            var targetRowsCount = target.RowsCount;
            var targetColumnsCount = target.ColumnsCount;
            var targetRowsBegins = target.RowsBegins;
            var targetColumns = target.ColumnsIndexes;
            var targetValues = target.Values;
            var sourceValues = source.Values;
            var sourceColumnsCount = source.ColumnsCount;

            var rowsCountToAssign = Math.Min(targetRowsIndexes.Length, source.RowsCount);
            var columnsCountToAssign = Math.Min(targetColumnsIndexes.Length, source.ColumnsCount);
            for (var rowIndex = 0; rowIndex < rowsCountToAssign; rowIndex++)
            {
                var rowElementIndex = targetRowsIndexes[rowIndex];

                #if SAFE

                if ((rowElementIndex < 0) || (targetRowsCount <= rowElementIndex))
                {
                    var argumentName = string.Format(CultureInfo.CurrentCulture, "targetRowsIndexes[{0}]", rowIndex);
                    throw new ElementIndexIsOutOfRangeException(argumentName, rowElementIndex, 0, targetRowsCount - 1);
                }

                #endif

                var targetStartIndex = targetRowsBegins[rowElementIndex];
                var targetEndIndex = targetRowsBegins[rowElementIndex + 1];

                var sourceElementIndex = rowIndex * sourceColumnsCount;

                for (var columnIndex = 0; columnIndex < columnsCountToAssign; columnIndex++)
                {
                    var columnElementIndex = targetColumnsIndexes[columnIndex];

                    #if SAFE

                    if ((rowIndex == 0) && ((columnElementIndex < 0) || (targetColumnsCount <= columnElementIndex)))
                    {
                        var argumentName = string.Format(CultureInfo.CurrentCulture, "targetColumnsIndexes[{0}]", columnIndex);
                        throw new ElementIndexIsOutOfRangeException(argumentName, columnElementIndex, 0, targetColumnsCount - 1);
                    }

                    #endif

                    var position = targetStartIndex;
                    while ((position < targetEndIndex) && (targetColumns[position] < columnElementIndex))
                    {
                        position++;
                    }

                    // if elements is not found, skip it
                    if ((position == targetEndIndex) || (targetColumns[position] != columnElementIndex))
                    {
                        #if SAFE

                        throw new ReadOnlyMatrixElementException("target", rowElementIndex, columnElementIndex);

                        #else

                        continue;

                        #endif
                    }

                    targetValues[position] = sourceValues[sourceElementIndex];

                    sourceElementIndex++;
                }
            }
        }

        /// <summary>
        ///     Sets the default value to all elements of the matrix.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="matrix">
        ///     The matrix that contains elements to clear.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="matrix"/> is <see langword="null"/>.
        /// </exception>
        public static void Clear<T>(this CrsSparseMatrix<T> matrix)
        {
            #if SAFE

            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            #endif

            Array.Clear(
                matrix.Values, matrix.RowsBegins[0], matrix.RowsBegins[matrix.RowsCount] - matrix.RowsBegins[0]);
        }

        /// <summary>
        ///     Sets the default value to all elements in the specified column of the matrix.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="matrix">
        ///     The matrix that contains the column to clear.
        /// </param>
        /// <param name="columnIndex">
        ///     The zero-based index of the column to clear.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="matrix"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ElementIndexIsOutOfRangeException">
        ///     <paramref name="columnIndex"/> is negative or greater than or equal to columns count.
        /// </exception>
        public static void ClearColumn<T>(this CrsSparseMatrix<T> matrix, int columnIndex)
        {
            #if SAFE

            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            if ((columnIndex < 0) || (matrix.ColumnsCount <= columnIndex))
            {
                throw new ElementIndexIsOutOfRangeException("columnIndex", columnIndex, 0, matrix.ColumnsCount - 1);
            }

            #endif

            var rowsBegins = matrix.RowsBegins;
            var columnsIndexes = matrix.ColumnsIndexes;
            var values = matrix.Values;

            var rowEnd = rowsBegins[0];

            var rowsCount = matrix.ColumnsCount;
            for (var rowIndex = 0; rowIndex < rowsCount; rowIndex++)
            {
                var elementIndex = rowEnd;
                rowEnd = rowsBegins[rowIndex + 1];
                while ((elementIndex < rowEnd) && (columnsIndexes[elementIndex] < columnIndex))
                {
                    elementIndex++;
                }

                if ((elementIndex < rowEnd) && (columnsIndexes[elementIndex] == columnIndex))
                {
                    values[elementIndex] = default(T);
                }
            }
        }

        /// <summary>
        ///     Sets the default value to all elements in the specified row of the matrix.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="matrix">
        ///     The matrix that contains the row to clear.
        /// </param>
        /// <param name="rowIndex">
        ///     The zero-based index of the row to clear.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="matrix"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ElementIndexIsOutOfRangeException">
        ///     <paramref name="rowIndex"/> is negative or greater than or equal to rows count.
        /// </exception>
        public static void ClearRow<T>(this CrsSparseMatrix<T> matrix, int rowIndex)
        {
            #if SAFE

            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            if ((rowIndex < 0) || (matrix.RowsCount <= rowIndex))
            {
                throw new ElementIndexIsOutOfRangeException("rowIndex", rowIndex, 0, matrix.RowsCount - 1);
            }

            #endif

            Array.Clear(
                matrix.Values,
                matrix.RowsBegins[rowIndex],
                matrix.RowsBegins[rowIndex + 1] - matrix.RowsBegins[rowIndex]);
        }

        /// <summary>
        ///     Creates a deep copy of the matrix.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="source">
        ///     The source matrix.
        /// </param>
        /// <returns>
        ///     A deep copy of the matrix.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="source"/> is <see langword="null"/>.
        /// </exception>
        /// <remarks>
        ///     This method doesn't create a deep copy of RowsBegins collection and ColumnsIndexes collection.
        /// </remarks>
        public static CrsSparseMatrix<T> Clone<T>(this CrsSparseMatrix<T> source)
        {
            #if SAFE

            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            #endif

            var result = new CrsSparseMatrix<T>(
                source.RowsCount, source.ColumnsCount, source.RowsBegins, source.ColumnsIndexes);
            Array.Copy(source.Values, result.Values, result.Values.Length);
            return result;
        }

        /// <summary>
        ///     Gets the element in the matrix at the specified location.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="matrix">
        ///     The matrix that contains the element to get.
        /// </param>
        /// <param name="rowIndex">
        ///     The zero-based index of row of the element to get.
        ///     </param>
        /// <param name="columnIndex">
        ///     The zero-based index of column of the element to get.
        /// </param>
        /// <returns>
        ///     The element in the matrix at the specified location.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="matrix"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ElementIndexIsOutOfRangeException">
        ///     <paramref name="rowIndex"/> is negative or greater than or equal to
        ///     the number of rows of <paramref name="matrix"/>.
        ///     <para>
        ///         --or--
        ///     </para>
        ///     <para>
        ///         <paramref name="columnIndex"/> is negative or greater than or equal to
        ///         the number of columns of <paramref name="matrix"/>.
        ///     </para>
        /// </exception>
        public static T GetAt<T>(this CrsSparseMatrix<T> matrix, int rowIndex, int columnIndex)
        {
            #if SAFE

            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            if ((rowIndex < 0) || (matrix.RowsCount <= rowIndex))
            {
                throw new ElementIndexIsOutOfRangeException("rowIndex", rowIndex, 0, matrix.RowsCount - 1);
            }

            if ((columnIndex < 0) || (matrix.ColumnsCount <= columnIndex))
            {
                throw new ElementIndexIsOutOfRangeException("columnIndex", columnIndex, 0, matrix.ColumnsCount - 1);
            }

            #endif

            var columnsIndexes = matrix.ColumnsIndexes;

            var elementIndex = matrix.RowsBegins[rowIndex];
            var rowEnd = matrix.RowsBegins[rowIndex + 1];
            while ((elementIndex < rowEnd) && (columnsIndexes[elementIndex] < columnIndex))
            {
                elementIndex++;
            }

            // if element is found, return it; otherwise, return default value for T type
            return (elementIndex == rowEnd) || (columnsIndexes[elementIndex] != columnIndex)
                       ? default(T)
                       : matrix.Values[elementIndex];
        }

        /// <summary>
        ///     Sets the element in the matrix at the specified location.
        /// </summary>
        /// <typeparam name="T">
        ///     The type of values of matrix elements.
        /// </typeparam>
        /// <param name="matrix">
        ///     The matrix that contains the element to set.
        /// </param>
        /// <param name="newValue">
        ///     The new value for the element.
        /// </param>
        /// <param name="rowIndex">
        ///     The zero-based index of row of the element to set.
        /// </param>
        /// <param name="columnIndex">
        ///     The zero-based index of column of the element to set.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="matrix"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ElementIndexIsOutOfRangeException">
        ///     <paramref name="rowIndex"/> is negative or greater than or equal to
        ///     the number of rows of <paramref name="matrix"/>.
        ///     <para>
        ///         --or--
        ///     </para>
        ///     <para>
        ///         <paramref name="columnIndex"/> is negative or greater than or equal to
        ///         the number of columns of <paramref name="matrix"/>.
        ///     </para>
        /// </exception>
        /// <exception cref="ReadOnlyMatrixElementException">
        ///     <paramref name="rowIndex"/> and <paramref name="columnIndex"/> specifies the element
        ///     that is not in the portrait of <paramref name="matrix"/>.
        /// </exception>
        public static void SetAt<T>(this CrsSparseMatrix<T> matrix, T newValue, int rowIndex, int columnIndex)
        {
            #if SAFE

            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            if ((rowIndex < 0) || (matrix.RowsCount <= rowIndex))
            {
                throw new ElementIndexIsOutOfRangeException("rowIndex", rowIndex, 0, matrix.RowsCount - 1);
            }

            if ((columnIndex < 0) || (matrix.ColumnsCount <= columnIndex))
            {
                throw new ElementIndexIsOutOfRangeException("columnIndex", columnIndex, 0, matrix.ColumnsCount - 1);
            }

            #endif

            var columnsIndexes = matrix.ColumnsIndexes;

            var elementIndex = matrix.RowsBegins[rowIndex];
            var rowEnd = matrix.RowsBegins[rowIndex + 1];
            while ((elementIndex < rowEnd) && (columnsIndexes[elementIndex] < columnIndex))
            {
                elementIndex++;
            }

            if ((elementIndex == rowEnd) || (columnsIndexes[elementIndex] != columnIndex))
            {
                #if SAFE

                throw new ReadOnlyMatrixElementException("matrix", rowIndex, columnIndex);

                #else

                return;

                #endif
            }

            matrix.Values[elementIndex] = newValue;
        }

        #endregion

        #endregion
    }
}